package com.os.osframe.scaffold.service.impl;

import com.os.osframe.scaffold.domain.AutoConfigModule;
import com.os.osframe.scaffold.domain.ConfigModules;
import com.os.osframe.scaffold.service.IConfigModuleService;
import com.os.osframe.scaffold.util.JaxbUtil;
import com.os.osframe.scaffold.util.PropertyConfigurerLoader;
import org.dom4j.Document;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by wangchun on 16/7/7.
 */

@Repository("configModuleService")
public class ConfigModuleServiceImpl implements IConfigModuleService,InitializingBean {
    protected static ConfigModules modules;
    @Resource
    protected PropertyConfigurerLoader propertyConfigurer;
    /**
     * 获取module对象
     * @param packageName
     * @return
     */
    public AutoConfigModule findModule(String packageName){
        if(packageName==null || "".equals(packageName.trim())){
            return null;
        }
        List<AutoConfigModule> list=this.getModuleList();
        if(list==null || list.isEmpty()){
            return null;
        }
        for(AutoConfigModule configModule:list){
            if(packageName.trim().equals(configModule.getLbPackage())){
                return configModule;
            }
        }
        return null;
    }
    /**
     * 获取module对象
     * @param id
     * @return
     */
    public AutoConfigModule findModuleId(String id){
        if(id==null || "".equals(id.trim())){
            return null;
        }
        List<AutoConfigModule> list=this.getModuleList();
        if(list==null || list.isEmpty()){
            return null;
        }
        for(AutoConfigModule configModule:list){
            if(id.trim().equals(configModule.getPkId())){
                return configModule;
            }
        }
        return null;
    }
    /**
     * 保存模块配置
     * @param configModule
     */
    public void saveModule(AutoConfigModule configModule){
        AutoConfigModule xmlConfigModule=this.findModule(configModule.getLbPackage());

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String nowDate=format.format(new Date());
        configModule.setLbUpdateTime(nowDate);
        if(xmlConfigModule!=null){//更新
            xmlConfigModule=configModule;
        }else{//保存
            this.getModuleList().add(configModule);
        }
        //刷新xml文件
        saveXmlConfig();
    }

    /**
     * 获取模块列表
     */
    public List<AutoConfigModule> getModuleList(){
        if(modules==null ){
            modules= new ConfigModules();
        }
        if(modules.getConfigModuleList()==null){
            modules.setConfigModuleList(new ArrayList());
        }
        return modules.getConfigModuleList();
    }

    /**
     * 初始化加载配置信息
     */
    public void initLoadConfig() {
        try {
            if(modules==null || modules.getConfigModuleList()==null ||modules.getConfigModuleList().isEmpty()){
                String basePath = (String) propertyConfigurer.getProperty("osframe.file.path");//获取属性配置的服务器路径
                if (basePath.substring(basePath.length() - 1).equals("/")) {
                    basePath = basePath.substring(basePath.length() - 1);
                }
                String modulePath = basePath + "/auto/config/module.xml";
                Document document = null;
                File file = new File(modulePath);
                if(file.exists()){//当文件存在时加载进来
                    SAXReader saxReader = new SAXReader();// 用来读取xml文档
                    document = saxReader.read(file);// 读取xml文档
                    String xml = document.asXML();
                    System.out.println(xml);
                    modules=JaxbUtil.converyToJavaBean(xml, ConfigModules.class);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 保存xml配置
     */
    public void saveXmlConfig(){
        try {
            String basePath = (String) propertyConfigurer.getProperty("osframe.file.path");//获取属性配置的服务器路径
            if (basePath.substring(basePath.length() - 1).equals("/")) {
                basePath = basePath.substring(basePath.length() - 1);
            }
            String modulePath = basePath + "/auto/config/module.xml";
            Document document = null;
            File file = new File(modulePath);
            String xml = JaxbUtil.convertToXml(modules, "UTF-8");
            BufferedWriter output = null;
            String moduleFolderPath=basePath + "/auto/config";
            File moduleFolder = new File(moduleFolderPath);
            if(!moduleFolder.exists()){
                moduleFolder.mkdirs();
            }
            file.createNewFile();//每次保存都采用覆盖方式
            output = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
            output.write(xml);
            output.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 删除指定的记录
     * @param id
     */
    public void delete(String id){
        if(id==null || "".equals(id.trim())){
            return ;
        }
        List<AutoConfigModule> list=this.getModuleList();
        if(list==null || list.isEmpty()){
            return ;
        }
        Boolean bool=false;//是否有变更
        for(int i=0,len=list.size();i<len;i++){
            AutoConfigModule configModule=list.get(i);
            if(id.trim().equals(configModule.getPkId())){
                list.remove(i);
                bool=true;
                break;
            }
        }
        if(bool){
            //更新xml配置文件
            saveXmlConfig();
        }

    }
    public void afterPropertiesSet() throws Exception {
        initLoadConfig();
    }
}
